document.addEventListener('DOMContentLoaded', function() {
    // 添加动画效果
    animateElements();
    
    // 注册导航事件监听
    setupNavigation();
    
    // 初始化小助手
    initializeAssistant();
    
    // 初始化其他页面特定功能
    if (document.querySelector('.question-container')) {
        initializeQuizPage();
    }
});

/**
 * 为页面元素添加动画效果
 */
function animateElements() {
    // 淡入效果
    const fadeInElements = document.querySelectorAll('.card');
    fadeInElements.forEach((element, index) => {
        element.style.opacity = '0';
        element.style.transform = 'translateY(20px)';
        element.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
        
        setTimeout(() => {
            element.style.opacity = '1';
            element.style.transform = 'translateY(0)';
        }, 100 * index);
    });
    
    // 为会员卡片添加鼠标悬停效果
    const membershipCards = document.querySelectorAll('.membership-card');
    membershipCards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-10px)';
            this.style.boxShadow = '0 15px 35px rgba(0, 0, 0, 0.15)';
        });
        
        card.addEventListener('mouseleave', function() {
            this.style.transform = '';
            this.style.boxShadow = '';
        });
    });
}

/**
 * 设置导航交互
 */
function setupNavigation() {
    // 平滑滚动到锚点
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            e.preventDefault();
            const targetId = this.getAttribute('href');
            
            if (targetId === '#') return;
            
            const targetElement = document.querySelector(targetId);
            if (targetElement) {
                window.scrollTo({
                    top: targetElement.offsetTop - 80,
                    behavior: 'smooth'
                });
            }
        });
    });
    
    // 添加导航栏滚动效果
    window.addEventListener('scroll', function() {
        const navbar = document.querySelector('.navbar');
        if (window.scrollY > 50) {
            navbar.style.padding = '0.5rem 1rem';
            navbar.style.boxShadow = '0 4px 10px rgba(0, 0, 0, 0.1)';
        } else {
            navbar.style.padding = '1rem';
            navbar.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.1)';
        }
    });

    // 设置答题专区下拉菜单行为
    const dropdownToggle = document.getElementById('answerAreaDropdown');
    const dropdownMenu = dropdownToggle?.nextElementSibling;
    
    if (dropdownToggle && dropdownMenu) {
        // 点击显示下拉菜单
        dropdownToggle.addEventListener('click', function(e) {
            e.preventDefault();
            this.classList.toggle('show');
            if (this.classList.contains('show')) {
                dropdownMenu.style.display = 'block';
            } else {
                dropdownMenu.style.display = 'none';
            }
        });
        
        // 鼠标移开时隐藏下拉菜单
        const dropdownContainer = dropdownToggle.parentElement;
        dropdownContainer.addEventListener('mouseleave', function() {
            dropdownToggle.classList.remove('show');
            dropdownMenu.style.display = 'none';
        });
    }
}

/**
 * 初始化虚拟小助手
 */
function initializeAssistant() {
    // 创建小助手元素
    const assistant = document.createElement('div');
    assistant.className = 'virtual-assistant';
    assistant.innerHTML = `
        <div class="assistant-avatar">
            <img src="images/assistant.png" alt="小助手">
        </div>
        <div class="assistant-bubble d-none">
            <p>你好！我是你的小助手，有什么问题可以问我哦！</p>
            <div class="assistant-buttons">
                <button class="btn btn-sm btn-primary assistant-btn">如何答题？</button>
                <button class="btn btn-sm btn-primary assistant-btn">获取提示</button>
            </div>
        </div>
    `;
    
    document.body.appendChild(assistant);
    
    // 小助手点击事件
    const avatarElement = assistant.querySelector('.assistant-avatar');
    const bubbleElement = assistant.querySelector('.assistant-bubble');
    
    avatarElement.addEventListener('click', function() {
        bubbleElement.classList.toggle('d-none');
    });
    
    // 小助手按钮事件
    const assistantButtons = assistant.querySelectorAll('.assistant-btn');
    assistantButtons.forEach(button => {
        button.addEventListener('click', function() {
            const buttonText = this.textContent;
            let response = '';
            
            if (buttonText === '如何答题？') {
                response = '点击选择正确的答案，答对了会有奖励哦！';
            } else if (buttonText === '获取提示') {
                response = '仔细观察图片的形状和颜色，找出它们的规律！';
            }
            
            const messageElement = bubbleElement.querySelector('p');
            messageElement.textContent = response;
            
            // 3秒后恢复原始消息
            setTimeout(() => {
                messageElement.textContent = '你好！我是你的小助手，有什么问题可以问我哦！';
            }, 3000);
        });
    });
    
    // 添加CSS
    const style = document.createElement('style');
    style.textContent = `
        .virtual-assistant {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 1000;
        }
        
        .assistant-avatar {
            width: 70px;
            height: 70px;
            border-radius: 50%;
            background-color: var(--primary-color);
            cursor: pointer;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            border: 3px solid #fff;
            transition: all 0.3s ease;
        }
        
        .assistant-avatar:hover {
            transform: scale(1.1);
        }
        
        .assistant-avatar img {
            width: 80%;
            height: 80%;
            object-fit: cover;
        }
        
        .assistant-bubble {
            position: absolute;
            bottom: 85px;
            right: 0;
            width: 250px;
            background-color: #fff;
            border-radius: 15px;
            padding: 15px;
            box-shadow: 0 5px 25px rgba(0, 0, 0, 0.15);
            border: 2px solid var(--primary-color);
        }
        
        .assistant-bubble:after {
            content: '';
            position: absolute;
            bottom: -10px;
            right: 25px;
            border-width: 10px 10px 0;
            border-style: solid;
            border-color: var(--primary-color) transparent;
        }
        
        .assistant-bubble p {
            margin-bottom: 10px;
            font-size: 0.9rem;
        }
        
        .assistant-buttons {
            display: flex;
            gap: 5px;
        }
        
        .assistant-btn {
            font-size: 0.8rem;
            padding: 0.25rem 0.5rem;
        }
    `;
    
    document.head.appendChild(style);
}

// 在实际答题页面添加的函数
function initializeQuizPage() {
    // 答题完成后的反馈函数
    function showFeedback(isCorrect) {
        const feedbackElement = document.createElement('div');
        feedbackElement.className = 'answer-feedback';
        
        if (isCorrect) {
            feedbackElement.innerHTML = `
                <div class="feedback-content correct-answer">
                    <h3>太棒了！</h3>
                    <p>你答对了！</p>
                    <div class="stars-container">
                        <span class="star">⭐</span>
                        <span class="star">⭐</span>
                        <span class="star">⭐</span>
                    </div>
                    <button class="btn btn-primary next-question-btn">下一题</button>
                </div>
            `;
            
            // 播放正确音效
            const correctSound = new Audio('sounds/correct.mp3');
            correctSound.play();
            
        } else {
            feedbackElement.innerHTML = `
                <div class="feedback-content wrong-answer">
                    <h3>再试一次</h3>
                    <p>别担心，再思考一下！</p>
                    <button class="btn btn-primary try-again-btn">再试一次</button>
                </div>
            `;
            
            // 播放错误音效
            const wrongSound = new Audio('sounds/wrong.mp3');
            wrongSound.play();
        }
        
        document.body.appendChild(feedbackElement);
        
        // 添加动画
        setTimeout(() => {
            feedbackElement.querySelector('.feedback-content').style.transform = 'scale(1)';
        }, 100);
        
        // 绑定按钮事件
        if (isCorrect) {
            feedbackElement.querySelector('.next-question-btn').addEventListener('click', function() {
                feedbackElement.remove();
                // 这里应该加载下一题的逻辑
            });
            
            // 星星动画
            const stars = feedbackElement.querySelectorAll('.star');
            stars.forEach((star, index) => {
                setTimeout(() => {
                    star.style.opacity = '1';
                    star.style.transform = 'translateY(0) rotate(0)';
                }, 300 * index);
            });
        } else {
            feedbackElement.querySelector('.try-again-btn').addEventListener('click', function() {
                feedbackElement.remove();
            });
        }
        
        // 添加CSS
        const style = document.createElement('style');
        style.textContent = `
            .answer-feedback {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.7);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 2000;
            }
            
            .feedback-content {
                background-color: #fff;
                border-radius: 20px;
                padding: 30px;
                text-align: center;
                max-width: 400px;
                transform: scale(0.8);
                transition: transform 0.3s ease;
            }
            
            .correct-answer h3 {
                color: #4CAF50;
            }
            
            .wrong-answer h3 {
                color: #FF5722;
            }
            
            .stars-container {
                margin: 20px 0;
            }
            
            .star {
                display: inline-block;
                font-size: 2.5rem;
                margin: 0 5px;
                opacity: 0;
                transform: translateY(20px) rotate(20deg);
                transition: opacity 0.3s ease, transform 0.5s ease;
            }
        `;
        
        document.head.appendChild(style);
    }
    
    // 示例调用
    // 正确答案反馈: showFeedback(true);
    // 错误答案反馈: showFeedback(false);
    
    // 拼图游戏逻辑
    function initializePuzzleGame(containerSelector, imageUrl, gridSize = 3) {
        const container = document.querySelector(containerSelector);
        if (!container) return;
        
        let pieces = [];
        let puzzleSolved = false;
        
        // 创建拼图
        function createPuzzle() {
            const puzzleContainer = document.createElement('div');
            puzzleContainer.className = 'puzzle-container';
            
            // 加载图片
            const img = new Image();
            img.src = imageUrl;
            img.onload = function() {
                const pieceWidth = img.width / gridSize;
                const pieceHeight = img.height / gridSize;
                
                // 创建拼图块
                for (let row = 0; row < gridSize; row++) {
                    for (let col = 0; col < gridSize; col++) {
                        const piece = document.createElement('div');
                        piece.className = 'puzzle-piece';
                        piece.style.width = `${100 / gridSize}%`;
                        piece.style.height = `${100 / gridSize}%`;
                        piece.style.backgroundImage = `url(${imageUrl})`;
                        piece.style.backgroundSize = `${gridSize * 100}% ${gridSize * 100}%`;
                        piece.style.backgroundPosition = `${col * 100 / (gridSize - 1)}% ${row * 100 / (gridSize - 1)}%`;
                        
                        piece.dataset.row = row;
                        piece.dataset.col = col;
                        
                        // 随机位置
                        piece.style.order = Math.floor(Math.random() * gridSize * gridSize);
                        
                        // 拖拽功能
                        piece.draggable = true;
                        piece.addEventListener('dragstart', handleDragStart);
                        piece.addEventListener('dragover', handleDragOver);
                        piece.addEventListener('drop', handleDrop);
                        
                        pieces.push(piece);
                        puzzleContainer.appendChild(piece);
                    }
                }
                
                container.appendChild(puzzleContainer);
                
                // 添加CSS
                const style = document.createElement('style');
                style.textContent = `
                    .puzzle-container {
                        width: 100%;
                        aspect-ratio: 1;
                        display: flex;
                        flex-wrap: wrap;
                        border: 3px solid var(--primary-color);
                        border-radius: 10px;
                        overflow: hidden;
                    }
                    
                    .puzzle-piece {
                        position: relative;
                        cursor: grab;
                        transition: transform 0.1s ease;
                    }
                    
                    .puzzle-piece:hover {
                        transform: scale(0.95);
                        z-index: 1;
                        box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
                    }
                    
                    .puzzle-piece:active {
                        cursor: grabbing;
                    }
                `;
                
                document.head.appendChild(style);
            };
        }
        
        // 拖拽事件处理
        function handleDragStart(e) {
            e.dataTransfer.setData('text/plain', e.target.style.order);
        }
        
        function handleDragOver(e) {
            e.preventDefault();
        }
        
        function handleDrop(e) {
            e.preventDefault();
            const sourceOrder = e.dataTransfer.getData('text/plain');
            const targetOrder = e.target.style.order;
            
            e.target.style.order = sourceOrder;
            this.style.order = targetOrder;
            
            // 检查是否完成
            checkPuzzleCompletion();
        }
        
        // 检查拼图是否完成
        function checkPuzzleCompletion() {
            let completed = true;
            
            pieces.forEach((piece) => {
                const row = parseInt(piece.dataset.row);
                const col = parseInt(piece.dataset.col);
                const correctOrder = row * gridSize + col;
                
                if (parseInt(piece.style.order) !== correctOrder) {
                    completed = false;
                }
            });
            
            if (completed && !puzzleSolved) {
                puzzleSolved = true;
                setTimeout(() => {
                    showFeedback(true);
                }, 500);
            }
        }
        
        createPuzzle();
    }
    
    // 示例调用
    // initializePuzzleGame('#puzzle-game', 'images/puzzle-image.jpg', 3);
    
    // 记忆卡牌游戏逻辑
    function initializeMemoryGame(containerSelector, cardCount = 8) {
        const container = document.querySelector(containerSelector);
        if (!container) return;
        
        const images = [
            'apple', 'banana', 'car', 'dog', 'elephant', 
            'fish', 'giraffe', 'house', 'ice-cream', 'jellyfish'
        ];
        
        let cards = [];
        let flippedCards = [];
        let matchedPairs = 0;
        
        // 创建记忆游戏
        function createMemoryGame() {
            // 选择卡片图像
            const selectedImages = images.slice(0, cardCount / 2);
            let cardImages = [...selectedImages, ...selectedImages];
            
            // 随机洗牌
            cardImages = cardImages.sort(() => Math.random() - 0.5);
            
            const gameContainer = document.createElement('div');
            gameContainer.className = 'memory-game-container';
            
            cardImages.forEach((image, index) => {
                const card = document.createElement('div');
                card.className = 'memory-card';
                card.innerHTML = `
                    <div class="memory-card-inner">
                        <div class="memory-card-front"></div>
                        <div class="memory-card-back">
                            <img src="images/cards/${image}.png" alt="${image}">
                        </div>
                    </div>
                `;
                
                card.dataset.image = image;
                card.addEventListener('click', flipCard);
                
                cards.push(card);
                gameContainer.appendChild(card);
            });
            
            container.appendChild(gameContainer);
            
            // 添加CSS
            const style = document.createElement('style');
            style.textContent = `
                .memory-game-container {
                    display: grid;
                    grid-template-columns: repeat(4, 1fr);
                    gap: 10px;
                    perspective: 1000px;
                }
                
                .memory-card {
                    height: 120px;
                    position: relative;
                    cursor: pointer;
                    transform-style: preserve-3d;
                    transform: scale(1);
                    transition: transform 0.2s;
                }
                
                .memory-card:hover {
                    transform: scale(0.97);
                }
                
                .memory-card-inner {
                    position: relative;
                    width: 100%;
                    height: 100%;
                    transform-style: preserve-3d;
                    transition: transform 0.5s;
                }
                
                .memory-card.flipped .memory-card-inner {
                    transform: rotateY(180deg);
                }
                
                .memory-card-front, .memory-card-back {
                    position: absolute;
                    width: 100%;
                    height: 100%;
                    backface-visibility: hidden;
                    border-radius: 10px;
                    overflow: hidden;
                }
                
                .memory-card-front {
                    background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
                    border: 3px solid #fff;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
                
                .memory-card-front:after {
                    content: '?';
                    font-size: 3rem;
                    color: #fff;
                    font-weight: bold;
                }
                
                .memory-card-back {
                    background: #fff;
                    transform: rotateY(180deg);
                    border: 3px solid var(--primary-color);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    padding: 10px;
                }
                
                .memory-card-back img {
                    max-width: 90%;
                    max-height: 90%;
                    object-fit: contain;
                }
                
                .memory-card.matched {
                    pointer-events: none;
                }
                
                .memory-card.matched .memory-card-back {
                    border-color: #4CAF50;
                    box-shadow: 0 0 10px rgba(76, 175, 80, 0.5);
                }
                
                @media (max-width: 768px) {
                    .memory-game-container {
                        grid-template-columns: repeat(3, 1fr);
                    }
                    
                    .memory-card {
                        height: 100px;
                    }
                }
            `;
            
            document.head.appendChild(style);
        }
        
        // 翻牌逻辑
        function flipCard() {
            // 如果已经翻开或已匹配则忽略
            if (this.classList.contains('flipped') || this.classList.contains('matched')) {
                return;
            }
            
            // 如果已经有两张牌翻开，则忽略
            if (flippedCards.length === 2) {
                return;
            }
            
            // 翻牌
            this.classList.add('flipped');
            flippedCards.push(this);
            
            // 如果翻开了两张牌，则检查是否匹配
            if (flippedCards.length === 2) {
                const firstCard = flippedCards[0];
                const secondCard = flippedCards[1];
                
                if (firstCard.dataset.image === secondCard.dataset.image) {
                    // 匹配成功
                    firstCard.classList.add('matched');
                    secondCard.classList.add('matched');
                    matchedPairs++;
                    
                    flippedCards = [];
                    
                    // 播放匹配音效
                    const matchSound = new Audio('sounds/match.mp3');
                    matchSound.play();
                    
                    // 检查游戏是否完成
                    if (matchedPairs === cardCount / 2) {
                        setTimeout(() => {
                            showFeedback(true);
                        }, 500);
                    }
                } else {
                    // 匹配失败，翻回去
                    setTimeout(() => {
                        firstCard.classList.remove('flipped');
                        secondCard.classList.remove('flipped');
                        flippedCards = [];
                    }, 1000);
                }
            }
        }
        
        createMemoryGame();
    }
    
    // 示例调用
    // initializeMemoryGame('#memory-game', 8);
}

// 模拟会员权益显示
function showMembershipDetails(type) {
    const details = {
        basic: {
            title: '基础会员',
            price: '免费',
            features: [
                '基础题目体验',
                '有限答题次数',
                '简单记录统计'
            ]
        },
        gold: {
            title: '黄金会员',
            price: '¥99/月',
            features: [
                '无限答题次数',
                '解锁全部专区题目',
                '参与专属活动',
                '获取限量奖励',
                '专属标识'
            ]
        },
        diamond: {
            title: '钻石会员',
            price: '¥199/月',
            features: [
                '黄金会员所有权益',
                '个性化训练计划定制',
                '优先参与线下活动',
                '专属客服支持',
                '家长训练报告分析'
            ]
        }
    };
    
    if (!details[type]) return;
    
    const membershipInfo = details[type];
    
    const detailModal = document.createElement('div');
    detailModal.className = 'membership-modal';
    detailModal.innerHTML = `
        <div class="membership-modal-content ${type}-membership">
            <span class="close-modal">&times;</span>
            <h3>${membershipInfo.title}</h3>
            <p class="price">${membershipInfo.price}</p>
            <hr>
            <h4>会员权益：</h4>
            <ul>
                ${membershipInfo.features.map(feature => `<li>${feature}</li>`).join('')}
            </ul>
            <button class="btn btn-lg btn-primary subscribe-btn">立即开通</button>
        </div>
    `;
    
    document.body.appendChild(detailModal);
    
    // 关闭按钮
    detailModal.querySelector('.close-modal').addEventListener('click', function() {
        detailModal.remove();
    });
    
    // 点击模态框外部关闭
    detailModal.addEventListener('click', function(e) {
        if (e.target === detailModal) {
            detailModal.remove();
        }
    });
    
    // 添加CSS
    const style = document.createElement('style');
    style.textContent = `
        .membership-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }
        
        .membership-modal-content {
            background-color: white;
            padding: 30px;
            border-radius: 15px;
            max-width: 500px;
            width: 90%;
            position: relative;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
        }
        
        .close-modal {
            position: absolute;
            top: 15px;
            right: 20px;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }
        
        .membership-modal-content h3 {
            font-size: 1.8rem;
            margin-bottom: 10px;
        }
        
        .membership-modal-content .price {
            font-size: 2rem;
            font-weight: bold;
            margin-bottom: 20px;
        }
        
        .membership-modal-content hr {
            margin: 20px 0;
        }
        
        .membership-modal-content ul {
            margin-bottom: 30px;
        }
        
        .membership-modal-content li {
            margin-bottom: 10px;
            font-size: 1.1rem;
            position: relative;
            padding-left: 25px;
        }
        
        .membership-modal-content li:before {
            content: "✓";
            position: absolute;
            left: 0;
            color: var(--primary-color);
            font-weight: bold;
        }
        
        .subscribe-btn {
            width: 100%;
            padding: 12px;
            font-size: 1.2rem;
        }
        
        .basic-membership .price {
            color: var(--primary-color);
        }
        
        .gold-membership .price,
        .gold-membership li:before {
            color: #ff9800;
        }
        
        .diamond-membership .price,
        .diamond-membership li:before {
            color: #673ab7;
        }
    `;
    
    document.head.appendChild(style);
} 